# -*- coding: utf-8 -*-
'''
测试 Grid Search
'''
from sklearn import datasets

digits = datasets.load_digits()

X = digits["data"]
y = digits["target"]

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y )


from sklearn.neighbors import KNeighborsClassifier
# 准备要测试的参数
param_grid = [
        {
            "weights":["uniform"],
            "n_neighbors":[i for i in range(1, 11)]
        },
        {
            "weights":["distance"],
            "n_neighbors":[i for i in range(1, 11)],
            "p":[i for i in range(1, 6)]
        }
]

# 创建一个knn对象
my_knn = KNeighborsClassifier()

from sklearn.model_selection import GridSearchCV
# n_jobs = -1,所有核全部参与工作
grid_search = GridSearchCV( my_knn, param_grid, n_jobs = -1 ) 
grid_search.fit( X_train, y_train )
grid_search.score( X_test, y_test )

grid_search.best_estimator_
''' 返回的是最适合的参数
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=1, p=2,
           weights='uniform')
'''
grid_search.best_score_
''' 最优的精确值
 0.98663697104677062
'''
grid_search.best_params_
''' 最适合的参数
{'n_neighbors': 1, 'weights': 'uniform'}
'''
